import { ref, defineComponent, onMounted, watch } from 'vue';
import { useRoute,useRouter } from 'vue-router';
import { getByCatalogId } from '@/api/document';
import { getCatalogTree } from '@/api/catalog';
import { Loading, Search, Home } from '@nutui/icons-vue';
import styles from './CatalogList.module.less';


// 注册PullRefresh组件
export default defineComponent({
  name: 'CatalogList',
 
  setup() {
    const title = ref('');
    const searchText = ref('');
    // 状态管理
    const documentList = ref([]);
    const loading = ref(false);
    const currentPage = ref(1);
    const pageSize = ref(10);
    const totalCount = ref(0);
    const error = ref('');
    const visible = ref(false)
    const navList = ref([
      {
        id: 1,
        text: '首页',
      },
    ])
    
    // 使用 useRoute 获取路由对象
    const route = useRoute();
    const router = useRouter();
    // 从路由参数中获取 catalogId
    const catalogId = ref(route.params.catalogId);
    console.warn('catalogId = ', catalogId.value);
    
    const onSearch = () => {
       router.push(`/search?docInfo=${searchText.value}`);
    };
  
    // 获取文档列表数据
    const fetchDocumentList = async (page, size) => {
      loading.value = true;
      error.value = '';
      
      try {
        const parameter = {
          catalogId: catalogId.value,
          page: page || currentPage.value,
          limit: size || pageSize.value
        };
        
        console.warn('parameter = ', parameter);
        
        const response = await getByCatalogId(parameter);
        
        if (response.data.code === 0) {
          documentList.value = response.data.data;
          totalCount.value = response.data.count;
        } else {
          // 接口返回失败
          documentList.value = [];
          totalCount.value = 0;
          error.value = '获取数据失败';
        }
      } catch (err) {
        documentList.value = [];
        totalCount.value = 0;
        error.value = '获取数据失败，请检查网络连接';
        console.error('获取文档列表失败:', err);
      } finally {
        loading.value = false;
      }
    };
    
    // 分页变化处理
    const handlePageChange = (page) => {
      currentPage.value = page;
      fetchDocumentList(page, pageSize.value);
    };
    
    
    // 处理文档点击事件
    const handleDocumentClick = (documentItem) => {
      if (documentItem.link_url) {
        // 去除链接中的空格
        const cleanUrl = documentItem.link_url.replace(/\s+/g, '');
        // 在新窗口打开链接
        window.open(cleanUrl, '_blank');
      }
    };

    const handleLinkPdfClick = (documentItem) => {
      if (documentItem.store_path) {
        // 去除链接中的空格
        const cleanUrl = documentItem.store_path.replace(/\s+/g, '');
        // 在新窗口打开链接
        // router.push(`/pdfPreview?url=${encodeURIComponent(cleanUrl)}`);
        //  router.push(`/pdfViewer?url=${encodeURIComponent(cleanUrl)}`);
            router.push(`/pdfRender?url=${encodeURIComponent(cleanUrl)}`);
      }
    };
    
    // 获取状态样式
    const getStatusClass = (status) => {
      switch (status) {
        case '正式版':
          return styles.statusOfficial;
        case '征求意见': return styles.statusDraft;
        default:
          return styles.statusDefault;
      }
    };
    

    
    // 监听路由参数变化，更新数据
    watch(() => route.params.catalogId, (newCatalogId) => {
      if (newCatalogId && newCatalogId !== catalogId.value) {
        catalogId.value = newCatalogId;
        currentPage.value = 1; // 切换目录时重置为第一页
        fetchDocumentList(1, pageSize.value);
      }
    });
    
    
    const initPage = () => {
      // 初始化页面数据
      fetchDocumentList(1, pageSize.value);
      if (catalogId.value) {
        getCatalogTree(catalogId.value).then(response => {
          if (response.data.code === 0) {
            // 这里可以根据需要处理获取到的分类树数据
            // 例如，可以用它来更新页面标题等
            title.value = response.data.data.name;
          }
        }).catch(error => {
          console.error('获取分类树数据失败:', error);
        });
      }
    };
    
    // 添加跳转首页函数
    const navigateToHome = () => {
      router.push('/');
    };
    
    initPage()
    return () => (
      <div class={styles.catalogList}>
        <div class={"navbar"}>
          <h3>{title.value}</h3>
        </div>
        <div class={styles.searchContainer}>
          <nut-searchbar v-model={searchText.value} onSearch={onSearch} placeholder="法规检索">
             {{
              leftin: () => <Search class={styles.searchIcon} size="18" />,
              rightin: () =><b onClick={onSearch}>搜索</b>
            }}
          </nut-searchbar>
        </div>
        
        {/* 添加固定导航 */}
        
        <nut-drag direction="y" style={{ left: '0px', bottom: '100px' }}>
            <nut-fixed-nav 
            type="left"
            v-model:visible={visible.value}
             >
              {{
                list: ()=>{
                  return <ul class="nut-fixed-nav__list">
                      <li class="nut-fixed-nav__list-item" onClick={navigateToHome}>首页</li>
                  </ul>
                }
              }}
             </nut-fixed-nav>
        </nut-drag>
        
          {/* 错误状态 */}
          {error.value && !loading.value && (
            <div class={styles.errorContainer}>
              <span>{error.value}</span>
              <button class={styles.retryButton} onClick={() => fetchDocumentList()}>
                重试
              </button>
            </div>
          )}
          
          {/* 列表内容 */}
          {!loading.value && documentList.value.length > 0 && (
            <div class={styles.listContainer}>
              {documentList.value.map((doc) => (
                <div 
                  key={doc.id} 
                  class={styles.documentItem} 
                  onClick={() => handleLinkPdfClick(doc)}
                >
                  <div class={styles.documentHeader}>
                    <h3 class={styles.documentTitle}>{doc.name}</h3>
                    
                  </div>
                  <div class={styles.documentFooter}>
                    <div>
                      <span class={styles.releaseDate}>发布:{doc.release_date}</span>
                      <span class={`${styles.documentStatus} ${getStatusClass(doc.status)}`}>
                        {doc.status}
                      </span>
                    </div>
                    
                     {/* <a href={ `${import.meta.env.VITE_APP_BASE_URL}/${doc.store_path}`} download={`${doc.name}.pdf`} target="_blank">下载</a> */}
                     <span  onClick={(e) => { e.stopPropagation(); handleDocumentClick(doc); }} class={styles.link}>原文链接</span>
                  </div>
                </div>
              ))}
            </div>
          )}
          
          {/* 空状态 */}
          {!loading.value && documentList.value.length === 0 && (
            <div class={styles.emptyContainer}>
              <span>暂无数据</span>
            </div>
          )}
          {totalCount.value > 0 && !loading.value && (
            <div class={styles.paginationContainer}>
              <nut-pagination
                show-page-size="3"
                force-ellipses
                totalItems={totalCount.value}
                v-model={currentPage.value}
                onChange={handlePageChange}
                showInfo={true}
              />
            </div>
          )}
      </div>
    );
  }
});

